package main

import (
	"context"
	"encoding/json"
	"fmt"
	"gin_study_blog/common"
	"gin_study_blog/core"
	"gin_study_blog/models"
	"github.com/olivere/elastic/v7"
	"github.com/sirupsen/logrus"
)

type TagsResponse struct {
	Tag             string   `json:"tag"`
	Count           int      `json:"count"`
	ArticleTagsList []string `json:"article_tags_list"`
}

type TagsType struct {
	DocCountErrorUpperBound int `json:"doc_count_error_upper_bound"`
	SumOtherDocCount        int `json:"sum_other_doc_count"`
	Buckets                 []struct {
		Key          string `json:"key"`
		DocCount     int    `json:"doc_count"`
		ArticleIndex struct {
			DocCountErrorUpperBound int `json:"doc_count_error_upper_bound"`
			SumOtherDocCount        int `json:"sum_other_doc_count"`
			Buckets                 []struct {
				Key      string `json:"key"`
				DocCount int    `json:"doc_count"`
			} `json:"buckets"`
		} `json:"article_index"`
	} `json:"buckets"`
}

func main() {
	// 读取配置文件
	core.YamlInitConfig()
	// 连接 es
	common.EsClient = core.EsConnect()
	/*
		{{"tag": "python", "article_count": 2, "article_list":[]}}
	*/

	agg := elastic.NewTermsAggregation().Field("tags")

	agg.SubAggregation("article_index", elastic.NewTermsAggregation().Field("keywords"))

	query := elastic.NewBoolQuery()

	result, err := common.EsClient.
		Search(models.ArticleModel{}.Index()).
		Query(query).
		Aggregation("tags", agg).
		Size(0).Do(context.Background())
	if err != nil {
		logrus.Error(err)
		return
	}

	var tagType TagsType
	tagData := make([]TagsResponse, 0)

	_ = json.Unmarshal(result.Aggregations["tags"], &tagType)
	for _, bucket := range tagType.Buckets {

		var articleList []string
		for _, s := range bucket.ArticleIndex.Buckets {
			articleList = append(articleList, s.Key)
		}

		tagData = append(tagData, TagsResponse{
			Tag:             bucket.Key,
			Count:           bucket.DocCount,
			ArticleTagsList: articleList,
		})
	}
	fmt.Println(tagData)
}
